<?php

namespace app\ports\controller\publics;

use app\ports\constants\TeamsConstants;
use think\Db;

/**
 * 团队 - 操作
 * Class
 * @package
 */
class Teams
{

	/**
	 * 对象实例
	 * @var object
	 */
	protected static $instance;

	protected $config = [
		"user" => "user"
	];

	protected $times = "";

	public function __construct($times = "")
	{
		if ($times) {
			$this->times = strtotime("+1 month", strtotime($times));
		}
	}

	/**
	 * 获取实例对象
	 * @return Binds|object
	 */
	public static function instance($times = "")
	{
		if (is_null(self::$instance)) {
			self::$instance = new static($times);
		}
		return self::$instance;
	}

	/**
	 * 获取可计算人员
	 */
	public function calc_able_personnel($pid)
	{
		$return = false;
		if (!empty($pid)) {
			$where = "pid = {$pid} and ptype = 2";
			if (!empty($this->times)) $where .= " and jointime < " . $this->times;
			$count = Db::name($this->config["user"])
				->where($where)
				->count();
			if ($count >= TeamsConstants::TEAMS_DEFULT_NUMS) {
				$return = true;
			}
		}
		return $return;
	}

	/**
	 * 所有直属下级
	 * @return array|bool
	 */
	public function _all_direct_level($pid)
	{
		if (!empty($pid)) {
			$where = "pid = {$pid}";
			if (!empty($this->times)) $where .= " and jointime < " . $this->times;
			$query = Db::name($this->config["user"])
				->field("id")
				->where($where)
				->select();
			if ($query) return $query;
		}
		return false;
	}

	/**
	 * 所有下级
	 * @return array
	 */
	public function _all_Lower_Level_teams_ids($pid, array &$array = [])
	{
		try {
			if (!empty($pid)) {
				$childLists = $this->framsChilds($pid);
				if ($childLists) {
					foreach ($childLists as $vals) {
						if ($vals["ptype"] == 2) {
							$array[] = $vals["id"];
						}
						$this->_all_Lower_Level_teams_ids($vals["id"], $array);
					}
				}
			}
		} finally {
			return $array;
		}
	}

	/**
	 * 管理架构 - 获取下级
	 * @param string $uniques
	 * @return array
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\DbException
	 * @throws \think\db\exception\ModelNotFoundException
	 */
	public function framsChilds($pid)
	{
		$data = []; //初始化返回参数
		try {
			if ($pid) {
				// 获取下级业务员
				$where = "pid = {$pid}";
				if (!empty($this->times)) $where .= " and jointime < " . $this->times;
				$query = Db::name($this->config["user"])
					->field("id,pid,ptype")
					->where($where)
					->select();
				if ($query) {
					$data = $query;
				}
			}
		} finally {
			return $data;
		}
	}
}
